//
//  WBNetworkManager.swift
//  CampusBlog
//
//  Created by 吴雷 on 2017/11/21.
//  Copyright © 2017年 吴雷. All rights reserved.
//

import UIKit
import AFNetworking

enum WBHTTPMethod {
    case GET
    case POST
}

class WBNetworkManager: AFHTTPSessionManager {
    //单例的写法
    static let shared: WBNetworkManager = {
        
        let instance = WBNetworkManager()
        
       // instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
        
    }()
    
    /// 访问令牌，所有网络请求，都基于此令牌（登录除外）
        var accessToken: String? = "2.00c7xgwC84e1pC6fc097eaba0Buj67"

    /// 专门负责拼接 token 的网络请求方法
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String,parameters: Any?,completion: @escaping (_ jsonObjct: Any?,_ isSuccess: Bool) -> ())  {
        
        // 处理 token 字典
        // 0> 判断 token 是否为 nil， 为 nil 直接返回
        guard let token = accessToken else {
            
            print("没有token，需要登录")
            
            completion(nil, false)
            
            return
          }
            
            // 1> 判断 参数字典是否存在， 如果为 nil ，应该新建一个字典
            var parameters = parameters as? [String: Any]
            
            if parameters == nil {
                // 实例化字典
                parameters = [String: Any]()
            }
            // 2> 设置参数字典,代码在此处一定有值
            parameters!["access_token"] = token
        
            request(method: method, URLString: URLString, parameters: parameters, completion: completion)
      }
 
        
        /// 封装 GET ／ POST 请求方法
        ///
        /// - parameter method:     GET ／ POST
        /// - parameter URLString:  URLString
        /// - parameter parameters: 请求参数字典
        /// - parameter completion: 完成回调
    func request(method: WBHTTPMethod = .GET, URLString: String,parameters: Any?,completion: @escaping (_ jsonObjct: Any?,_ isSuccess: Bool) -> ()) {


            let success = {(task: URLSessionDataTask, data: Any?) in
                completion(data, true)
            }

            let failure = { (task: URLSessionDataTask?, error: Error) in

                if (task?.response as? HTTPURLResponse)?.statusCode == 403 {

                    print("token 过期了！！！！")
                }
                
                print("网络请求错误\(error)")
                
                completion(nil, false)
            }

            if method == .GET {
                get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            }else {
                post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            }

        }

   }




